package cool.taomu.toolkit.cacheable

import com.google.common.cache.Cache
import java.util.Map
import javax.inject.Provider
import com.google.common.cache.CacheBuilder
import java.util.concurrent.TimeUnit
import com.google.inject.Inject
import com.google.inject.name.Named

class GuavaCacheProvider implements Provider<Cache<String, byte[]>> {

    @Inject
    @Named("taomu.cacheable.config.guava")
    Map<String, Object> config;

    override get() {
        if ((config.get("type") as String).equalsIgnoreCase("guava")) {
            var cache = CacheBuilder.newBuilder()
            if (config.containsKey("maximumSize")) {
                cache.maximumSize(config.get("maximumSize") as Long)
            } else {
                cache.maximumSize(1000)
            }
            if (config.containsKey("expireAfterWrite")) {
                var expireAfterWrite = Integer.toString(config.get("expireAfterWrite") as Integer)
                cache.expireAfterWrite(Long.parseLong(expireAfterWrite), TimeUnit.SECONDS)
            } else {
                cache.expireAfterWrite(5, TimeUnit.MINUTES)
            }
            if (config.containsKey("expireAfterAccess")) {
                var expireAfterAccess = Integer.toString(config.get("expireAfterAccess") as Integer)
                cache.expireAfterAccess(Long.parseLong(expireAfterAccess), TimeUnit.SECONDS)
            }
            return cache.build();
        }
    }

}
